﻿using System;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using NguyenHoa.Web.App_Code;
using DevExpress.Web.ASPxGridView;
using System.Web.UI.HtmlControls;

namespace NguyenHoa.Web.Admin
{
  public partial class GroupDetail : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;

   

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Group;
      }
    }

    private int GroupId
    {
      get
      {
        int grpId = 0;
        if (!String.IsNullOrEmpty(Request.QueryString["Id"]))
          int.TryParse(Request.QueryString["Id"], out grpId);
        return grpId;
      }
    }

    #endregion

    #region Methods
    private void InitPage()
    {
      if (GroupId <= 0)
      {
        Response.Redirect("Groups.aspx");
      }
      xdsStatus.DataFile = XmlStatusFile;
    }

    private void LoadUserOfGroup()
    {
      gvGroupMember.DataSource = new UserService().GetByGroupId(GroupId);
      gvGroupMember.DataBind();
    }

    private void LoadUserToSelect()
    {
      gvUser.DataSource = new UserService().GetUserNotInGroup(GroupId);
      gvUser.DataBind();
    }

    private string AddUsers()
    {
      try
      {
        UserGroupService ugService = new UserGroupService();
        TList<UserGroup> userList = new TList<UserGroup>();
        for (int i = 0; i < gvUser.VisibleRowCount; i++)
        {
          if (!gvUser.Selection.IsRowSelected(i)) continue;
          UserGroup user = new UserGroup();
          user.GroupId = GroupId;
          user.Username = gvUser.GetRowValues(i, "Username").ToString();
          userList.Add(user);
        }
        ugService.Save(userList);
      }
      catch (Exception ex)
      {
        WriteLog("GroupDetail.aspx:Add Users", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string DeleteUsers()
    {
      try
      {
        UserGroupService ugService = new UserGroupService();
        using (ConnectionScope.CreateTransaction())
        {
          for (int i = 0; i < gvGroupMember.VisibleRowCount; i++)
          {
            if (!gvGroupMember.Selection.IsRowSelected(i)) continue;
            int id = 0;
            int.TryParse(gvGroupMember.GetRowValues(i, "UserGroupId").ToString(), out id);
            ugService.Delete(id);
          }
          ConnectionScope.Complete();
        }
      }
      catch (Exception ex)
      {
        WriteLog("GroupDetail.aspx:Delete Users", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsCallback && !IsPostBack)
      {
        InitPage();
        LoadUserOfGroup();
        if (!CanModify) btnAdd.Visible = false;
        if (!CanDelete) btnDelete.Visible = false;
      }
      if (gvUser.IsCallback)
        LoadUserToSelect();
      if (gvGroupMember.IsCallback)
        LoadUserOfGroup();
    }

    protected void gvUser_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Load")
      {
        LoadUserToSelect();
      }
    }

    protected void gvGroupMember_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Add")
      {
        m_innerError = AddUsers();
        LoadUserOfGroup();
      }
      else if (para[0] == "Delete")
      {
        m_innerError = DeleteUsers();
        LoadUserOfGroup();
      }
    }

    protected void gvGroupMember_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvPermission_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvPermission_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
    {
      if (e.DataColumn.FieldName != "Approve") return;
      ASPxGridView grid = sender as ASPxGridView;
      HtmlInputCheckBox checkbox = grid.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "ckbApprove") as HtmlInputCheckBox;
      if (checkbox == null) return;
      checkbox.Attributes.Add("onclick", "onApproveSelected('" + e.VisibleIndex + "','" + checkbox.ClientID + "')");
      hfApproveCheckbox.Value += checkbox.ClientID + "|";
      hfApproveValue.Value += (e.CellValue.ToString() == "1") ? "true|" : "false|";
    }
    #endregion
  }
}
